/*
 * Copyright (C) 2009 CodeWerkz
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.codewerkz.prompty;

import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

/**
 * Class for the editing of a slide.
 * 
 * @author ChaZ
 */
public class SlideEdit extends Activity implements View.OnClickListener {

	private EditText mTitleText;
    private EditText mBodyText;
    private EditText mPromptDelay;
    private Long mRowId;
    private int mPresId;
    private SlidesDbAdapter mDbHelper;
    private Button mConfirmButton;

    //private static final String TAG = "Prompty - SlEdit";
    
    /**
     * Runs when Activity is created.
     * 
     * @return void
     */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    	super.onCreate(savedInstanceState);
    	
    	// Load the layout.
    	setContentView(R.layout.slide_edit);
    	
    	// Create the database object and open the connection.
        mDbHelper = new SlidesDbAdapter(this);
        mDbHelper.open();
        
        // Set up the views.       
        this.mTitleText = (EditText) this.findViewById(R.id.slideEdit_txtTitle);
        this.mBodyText = (EditText) this.findViewById(R.id.slideEdit_txtBody);
        this.mPromptDelay = (EditText) this.findViewById(R.id.slideEdit_delay);
        this.mConfirmButton = (Button) this.findViewById(R.id.slideEdit_btnSave);
       
        // Check if we have exited and been given the ID back.
        mRowId = savedInstanceState != null ? savedInstanceState.getLong(SlidesDbAdapter.KEY_ROWID) 
                							: null;
        
        // If the row ID is null then...
		if (mRowId == null) {
			// Create a  bundle and get the extras from the intent sent.
			Bundle extras = getIntent().getExtras();
			
			// Grab the Row Id.
			mRowId = extras != null ? extras.getLong(SlidesDbAdapter.KEY_ROWID) 
									: null;
			
			// Try and get the Presentation ID.
			try {
				mPresId = extras != null ? Integer.parseInt(extras.getString(SlidesList.PRESID))
											: null;
			} catch (NumberFormatException e) {
			// If it fails, then set the presentation id to 0.
				mPresId = 0;
			}
		}

		// Populate the layout with the data.
		populateFields();
		
		// Create a button listener for the Save button.
        this.mConfirmButton.setOnClickListener(this);  
    }
    
    /**
     * Runs when an onClick listener is triggered.
     * 
     * @param v View Id of the button clicked.
     * @return void
     */
    @Override
    public void onClick(View v) {
    	// If the view is a btn..
    	if(v == this.mConfirmButton) {         
    		// Set the result and finish.
    	    setResult(RESULT_OK);
    	    finish();
    	} 
    }
    
    /**
     * Runs when Activity is saves the instance.
     * 
     * @return void
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putLong(SlidesDbAdapter.KEY_ROWID, mRowId);
    }
    
    /**
     * Runs when the Activity pauses to make sure data is saved.
     * 
     * @return void
     */
    @Override
    protected void onPause() {
        super.onPause();
        // Save the state to prevent data loss.
        saveState();
    }
    
    /**
     * Runs when the Activity is about to be destroyed for garbage collection.
     * 
     * @return void
     */
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	// Prevents database leak
    	mDbHelper.close();
    }
    
    /**
     * Runs when the Activity is resumed.
     * 
     * @return void
     */
    @Override
    protected void onResume() {
        super.onResume();
        // Re-populate the fields.
        populateFields();
    }

    /**
     * Populates the fields.
     * 
     * @return void
     */
    private void populateFields() {
    	// Check if the row ID is (NOT NULL) AND (NOT 0).
        if (mRowId != null && mRowId != 0) {
        	
        	// If so, set up a cursor to the slide.
            Cursor pres = mDbHelper.fetchSlide(mRowId);
            
            // Manage the cursor and set the views to the correct data. 
            startManagingCursor(pres);
            
            mTitleText.setText(pres.getString(
            		pres.getColumnIndexOrThrow(SlidesDbAdapter.KEY_STITLE)));
            mBodyText.setText(pres.getString(
            		pres.getColumnIndexOrThrow(SlidesDbAdapter.KEY_STEXT)));
            mPromptDelay.setText(Integer.toString(pres.getInt(
            		pres.getColumnIndexOrThrow(SlidesDbAdapter.KEY_DELAY))));
        }
    }
   
    /**
     * Saves the state to prevent loss of data.
     * 
     * @return void
     */
    private void saveState() {
    	int delay = 0;
    	
    	// Get the text from the layout.
        String title = mTitleText.getText().toString();
        String body = mBodyText.getText().toString();
        try {
        	delay = Integer.parseInt(this.mPromptDelay.getText().toString());
        } catch (Exception e) {
        	delay = 0;
        }

        // TODO: Results
        // If the row Id (IS NULL) OR (EQUAL TO 0), this means that the slide
        // doesn't exist yet, so let us create it...
        if (mRowId == null || mRowId == 0) {
        	// Validate the title (body can be blank)
        	if (title.length() != 0) {
        		// Create the new slide and set the row id to the id of the new slide.
	            long id = mDbHelper.createSlide(mPresId, title, body, delay);
	            if (id > 0) {
	                mRowId = id;
	            }
        	}
        // Otherwise, we need to update the slide.
        } else {
        	// Validate the title and then update the slide.
        	if (title.length() != 0) {
        		mDbHelper.updateSlide(mRowId, title, body, delay);
        	} else {
        		// Do nothing.
        	}
        }
    }
    
}
